

g_sendPort  = 30334;
g_recvPort  = 30335;
g_Host      = "127.0.0.1" 

Device = {}
Device.__index = Device;

function Device.create()
	local dev = {}
	setmetatable(dev, Device);
	return dev;
end

function Device.get_argument_value(argNumber)
	return math.random();
end

function Device.performClickableAction(id, value)
    print("click action performed");
end

function GetDevice(deviceId)
	return Device.create();
end


g_IdToName = 
{
	-- Engines
	  --(left)
	[70] = "LeftEngineTemperatureUntis", -- LeftEngineTemperatureUnits
	[71] = "LeftEngineTemperatureTenth", -- LeftEngineTemperatureTenth
	[76] = "LeftFanSpeedIndicator", -- LeftFanSpeedInidicator
	[78] = "LeftCoreSpeedIndicatorUnits", -- LeftCoreSpeedIndicatorUnits
	[79] = "LeftCoreSpeedIndicatorTenth", -- LeftCoreSpeedIndicatorThenth
	[82] = "LeftEngineOilPressure", --LeftEngineOilPressure
	[84] = "LeftEngineFuelFlowIndicator",
		--(right)
	[73] = "LeftEngineTemperatureUntis",
	

	-- HSI
	
	-- ADI
};

g_OldValues = {}


function ValueHasChanged(index, newValue)
	return g_OldValues[index] ~= newValue; -- convert to epsilon convert later 
end

function LuaExportStart()
  print("LuaExportStart");
  --package.path = package.path.."C:\\Software\\Games\\Steam\\steamapps\\common\dcs a-10c warthog\\LuaSocket\\?.lua"
  --package.cpath = package.cpath.."C:\\Software\\Games\\Steam\\steamapps\\common\dcs a-10c warthog\\LuaSocket\\?.dll"
  --package.path  = package.path..";.\\LuaSocket\\?.lua"
  --package.cpath = package.cpath..";.\\LuaSocket\\?.dll"
  socket = require("socket")
  c = socket.udp();
  socket.try(c:setsockname(g_Host, g_recvPort));
  socket.try(c:settimeout(0.001));

  for i,name in ipairs(g_IdToName) do
	g_OldValues[i] = 0.0;
  end
  --send a handshake to the server
  socket.try(c:sendto("<hs>DcsA10;DCS A10</hs>", g_Host, g_sendPort))

end

function LuaExportBeforeNextFrame()
	print("exportbefore");
	g_Received = c:receive();
	if g_Received then
	    print("received: " .. g_Received);   
        if ProcessCommands(g_Received) == false then 
            print("Received invalid packet, buffer will be cleared -> maybe some commands got lost");
        end
	end
end

function ProcessCommands(input)

    local s1, e1 = string.find(input, "<cmds>");
    local s2, e2 = string.find(input, "</cmds>");

    if s1 == nil or e1 == nil or s2 == nil or e2 == nil then
        return false;
    end

    local cmdString     = string.sub(input, e1 + 1, s2 - 1);
    local cmds          = Split(cmdString, ';')

    for index, content in pairs(cmds) do
        print("content: " .. content);
        local id        = Split(content, '=')[1];
        local value     = Split(content, '=')[2];
        print("id: " .. id);
        print("value: " .. value);

        ExecuteSetValue(id, value);

    end


    return true;
end

function ExecuteSetValue(argNumber, value)
    local device = GetDevice(0)
	if type(device) == "table" then
        print("performing clickable Action");
	    device:performClickableAction(argNumber, value);	
	end    
end

function LuaExportActivityNextEvent(t)
	local tNext = t

	print("LuaExportNextEvent");

	local dataToSend = "";
	
	local device = GetDevice(0);
	
	for i, name in pairs(g_IdToName) do
		local value = device:get_argument_value(i);
		--print(string.format("%f", value));
		if ValueHasChanged(i, value) then
			g_OldValues[i] = value;
			dataToSend = dataToSend .. string.format("%i=%.2f;", i, value);
		end
	end
  
	--print("Sending: " .. dataToSend);
	socket.try(c:sendto(string.format("<data>%s</data>", dataToSend), g_Host, g_sendPort));	
	tNext = tNext + 0.5

	return tNext
end

-- Compatibility: Lua-5.0
function Split(str, delim, maxNb)
    -- Eliminate bad cases...
    if string.find(str, delim) == nil then
        return { str }
    end
    if maxNb == nil or maxNb < 1 then
        maxNb = 0    -- No limit
    end
    local result = {}
    local pat = "(.-)" .. delim .. "()"
    local nb = 0
    local lastPos
    for part, pos in string.gfind(str, pat) do
        nb = nb + 1
        result[nb] = part
        lastPos = pos
        if nb == maxNb then break end
    end
    -- Handle the last field
    if nb ~= maxNb then
        result[nb + 1] = string.sub(str, lastPos)
    end
    return result
end